import { Field } from "@prisma/client";
import dayjs from "dayjs";

import { getter } from "./getter";

type Intact = Record<string, any>;

/**
 * {"conversations": [{"role": "user", "content": "我想找一个男生"}, {"role": "assistant", "content": "<user>1008611</user>"}]}
 */

// 蒸馏池模板
const template = [
  // 基础版（优化语序）
  // `寻找#{address}的#{sex}，身高#{height}，#{birthday}出生，#{diplomas}学历，月收入#{monthly}，房产#{house}，车辆#{vehicle}`,

  // 场景化版（增加社交动机）
  // `希望认识来自#{address}的#{sex}，要求身高#{height}、生日#{birthday}，学历#{diplomas}，月薪#{monthly}，期待对方有#{house}房产和#{vehicle}`,

  // 简洁版（省略部分连接词）
  `<item>现居#{address}|性别#{sex}|身高#{height}|生日#{birthday}|学历#{diplomas}|月薪#{monthly}|房产#{house}|车辆#{vehicle}-#{id}</item>`,
];

// 定义变量池
const variables = [
  "address",
  "sex",
  "height",
  "birthday",
  "diplomas",
  "monthly",
  "house",
  "vehicle",
];

// 定义修饰算子
const operators = ["必须", "优先", "要求", "寻找", "期待", "接受", "诚寻"];

// 基础模板生成函数
function generateBaseTemplates() {
  const templates: string[] = [];
  // 生成单变量模板
  variables.forEach((variable) => {
    templates.push(`要求#{${variable}}`);
  });
  // 生成多变量组合模板
  for (let i = 2; i <= variables.length; i++) {
    const combinations = getCombinations(variables, i);
    combinations.forEach((combo: string[]) => {
      templates.push(`要求#{${combo.join("}+#{")}}`);
    });
  }
  return templates;
}

// 带修饰算子的模板生成函数
function generateOperatorTemplates() {
  const templates: string[] = [];
  variables.forEach((variable) => {
    operators.forEach((op) => {
      templates.push(`#{${variable}}[${op}]`);
    });
  });
  return templates;
}

// 工具函数：获取组合
function getCombinations(array: string[], size: number) {
  const result: string[][] = [];
  function backtrack(start: number, path: string[]) {
    if (path.length === size) {
      result.push([...path]);
      return;
    }
    for (let i = start; i < array.length; i++) {
      path.push(array[i]);
      backtrack(i + 1, path);
      path.pop();
    }
  }
  backtrack(0, []);
  return result;
}

function generatePureTemplates() {
  const baseTemplates = generateBaseTemplates();
  const operatorTemplates = generateOperatorTemplates();
  // 合并所有模板
  const allTemplates = [...baseTemplates, ...operatorTemplates];
  // 截取前 100 个
  return allTemplates;
}

const replace = (text: string, data: Record<string, any>) => {
  return text.replace(/#\{(\w+)\}/g, (match, key) => data[key] || match);
};

export const generate = (map: Record<string, Field>, user: Intact) => {
  const height = getter(map, "height", user.height);
  const birthday = dayjs(getter(map, "birthday", user.birthday)).format("YY年");
  const address = getter(map, "address", user.userInfo?.address);
  const nativeplace = getter(map, "jgAddress", user.userInfo?.jgAddress);
  const profession = getter(map, "profession", user.profession);
  const diplomas = getter(map, "diplomas", user.diplomas);
  const marital = getter(map, "marital_status", user.maritalStatus);
  const monthly = getter(map, "monthly_salary_type", user.monthlySalaryType);
  const house = getter(map, "house_property", user.houseProperty);
  const vehicle = getter(map, "vehicle", user.vehicle);
  const sex = getter(map, "sex", user.sex) === 1 ? "男生" : "女生";
  const id = user.userId;

  const pure = generatePureTemplates();

  const result = [...template].map((item) =>
    replace(item, {
      id,
      sex,
      height,
      birthday,
      address,
      nativeplace,
      profession,
      diplomas: diplomas || "不限",
      marital: marital || "不限",
      monthly: monthly || "不限",
      house: house || "不限",
      vehicle: vehicle || "不限",
    })
  );

  const jsonl = transverter(result, user.userId);

  return jsonl;
};

// 转为jsonl
const transverter = (result: string[], id: string) => {
  return result
  // return result.map((item) => ({
  //   messages: [
  //     {
  //       role: "system",
  //       content: "你是一个相亲平台，需要根据用户的要求，寻找符合条件的用户",
  //     },
  //     { role: "user", content: item },
  //     { role: "assistant", content: `<user>${id}</user>` },
  //   ],
  // }));
};
